<template>
  <a-modal
    v-model:open="modalOpen"
    title="完善账号信息"
    :width="500"
    :closable="false"
    :mask-closable="false"
    :footer="null"
    :centered="true"
  >
    <div class="bind-info-container">
      <!-- 头部信息 -->
      <div class="bind-header">
        <div class="provider-info">
          <component :is="getProviderIcon(provider)" class="provider-icon" />
          <div class="provider-text">
            <h3>{{ getProviderName(provider) }}登录</h3>
            <p>首次登录，请完善账号信息</p>
          </div>
        </div>
      </div>

      <!-- 表单 -->
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
        class="bind-form"
      >
        <a-form-item label="手机号" name="phone">
          <a-input
            v-model:value="formData.phone"
            placeholder="请输入手机号"
            size="large"
            prefix="📱"
          />
        </a-form-item>

        <a-form-item label="昵称" name="nickname">
          <a-input
            v-model:value="formData.nickname"
            placeholder="请输入昵称"
            size="large"
            prefix="👤"
          />
        </a-form-item>

        <a-form-item label="角色信息">
          <div class="role-info">
            <a-tag :color="getRoleColor(role)" size="large">
              {{ getRoleName(role) }}
            </a-tag>
            <span class="role-desc">系统将自动分配此角色</span>
          </div>
        </a-form-item>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <a-button
            type="primary"
            size="large"
            block
            @click="handleSubmit"
            :loading="submitting"
          >
            完成注册并登录
          </a-button>
          
          <a-button
            size="large"
            block
            @click="handleCancel"
            style="margin-top: 12px;"
          >
            取消
          </a-button>
        </div>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { bindAndLogin } from '@/api/user/sysOAuth2Controller'
import {
  WechatOutlined,
  VideoCameraOutlined,
  ShopOutlined,
  UserOutlined
} from '@ant-design/icons-vue'

interface Props {
  open: boolean
  provider: string
  code: string
  role: string
}

interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'bind-success', userData: any): void
  (e: 'bind-cancel'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 计算属性用于v-model:open
const modalOpen = computed({
  get: () => props.open,
  set: (value: boolean) => emit('update:open', value)
})

// 表单引用
const formRef = ref()

// 表单数据
const formData = ref({
  phone: '',
  nickname: ''
})

// 表单验证规则
const formRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在2-20个字符', trigger: 'blur' }
  ]
}

// 提交状态
const submitting = ref(false)

// 获取第三方平台图标
const getProviderIcon = (provider: string) => {
  switch (provider) {
    case 'wechat':
      return WechatOutlined
    case 'douyin':
      return VideoCameraOutlined
    case 'merchant_platform':
      return ShopOutlined
    case 'channel_user':
      return UserOutlined
    default:
      return UserOutlined
  }
}

// 获取第三方平台名称
const getProviderName = (provider: string) => {
  switch (provider) {
    case 'wechat':
      return '微信'
    case 'douyin':
      return '抖音'
    case 'merchant_platform':
      return '商户平台'
    case 'channel_user':
      return '渠道用户'
    default:
      return '第三方平台'
  }
}

// 获取角色名称
const getRoleName = (role: string) => {
  switch (role) {
    case 'student':
      return '学员'
    case 'merchant':
      return '商户'
    case 'user':
      return '用户'
    default:
      return '用户'
  }
}

// 获取角色颜色
const getRoleColor = (role: string) => {
  switch (role) {
    case 'student':
      return 'blue'
    case 'merchant':
      return 'green'
    case 'user':
      return 'purple'
    default:
      return 'default'
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate()
    
    submitting.value = true
    
    // 临时保存用户输入的昵称，用于前端显示
    localStorage.setItem('temp_nickname', formData.value.nickname)
    
    // 调用绑定接口
    const result = await bindAndLogin({
      provider: props.provider,
      code: props.code,
      phone: formData.value.phone,
      nickname: formData.value.nickname
    })
    
    if ((result as any).code === '00000' && result.data) {
      // 移除冗余的成功消息，让HomeView处理登录成功通知
      emit('bind-success', result.data)
      emit('update:open', false)
    } else {
      throw new Error((result as any).msg || '注册绑定失败')
    }
    
  } catch (error: any) {
    if (error.errorFields) {
      // 表单验证错误
      return
    }
    console.error('注册绑定失败:', error)
    
    // 处理后端抛出的具体异常
    let errorMessage = error.message || '注册绑定失败，请重试'
    
    // 检查是否是后端返回的具体错误信息
    if (error.response?.data?.msg) {
      errorMessage = error.response.data.msg
    }
    
    // 如果是网络错误，给出更友好的提示
    if (error.code === 'NETWORK_ERROR' || error.message?.includes('Network Error')) {
      errorMessage = '网络连接失败，请检查网络后重试'
    }
    
    // 处理频率限制等特殊错误
    if (errorMessage.includes('操作过于频繁')) {
      errorMessage = '操作过于频繁，请稍后再试'
    }
    
    // 处理第三方平台不支持的错误
    if (errorMessage.includes('该第三方暂不支持登录')) {
      errorMessage = '该第三方平台暂不支持登录，请选择其他方式'
    }
    
    message.error(errorMessage)
  } finally {
    submitting.value = false
  }
}

// 取消操作
const handleCancel = () => {
  emit('bind-cancel')
  emit('update:open', false)
}

// 组件挂载时设置默认昵称
onMounted(() => {
  formData.value.nickname = `用户${Math.floor(Math.random() * 10000)}`
})
</script>

<style scoped>
.bind-info-container {
  padding: 20px 0;
}

.bind-header {
  margin-bottom: 24px;
  text-align: center;
}

.provider-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
}

.provider-icon {
  font-size: 48px;
  color: #1890ff;
}

.provider-text h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
  color: #333;
}

.provider-text p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.bind-form {
  max-width: 400px;
  margin: 0 auto;
}

.role-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.role-desc {
  font-size: 14px;
  color: #666;
}

.form-actions {
  margin-top: 24px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .bind-info-container {
    padding: 16px 0;
  }
  
  .provider-info {
    flex-direction: column;
    gap: 12px;
  }
  
  .provider-icon {
    font-size: 40px;
  }
}
</style>
